// 设置页面JavaScript

// 全局变量
let currentPage = 1;
let pageSize = 10;
let currentCategory = '';
let currentModelType = '';

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initSettingsPage();
});

// 初始化设置页面
function initSettingsPage() {
    // 绑定标签页切换事件
    bindTabEvents();
    
    // 加载基础设置
    loadBasicSettings();
    
    // 加载模型列表
    loadModelList();
}

// 绑定标签页事件
function bindTabEvents() {
    const tabs = document.querySelectorAll('.settings-tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.dataset.tab;
            switchTab(tabName);
        });
    });
}

// 切换标签页
function switchTab(tabName) {
    // 更新标签页状态
    document.querySelectorAll('.settings-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
    
    // 显示对应内容
    document.querySelectorAll('.settings-content').forEach(content => {
        content.style.display = 'none';
    });
    
    if (tabName === 'basic') {
        const basicSettings = document.getElementById('basic-settings');
        if (basicSettings) {
            basicSettings.style.display = 'flex';
            basicSettings.style.flexDirection = 'column';
        }
        loadBasicSettings();
    } else if (tabName === 'models') {
        const modelSettings = document.getElementById('model-settings');
        if (modelSettings) {
            modelSettings.style.display = 'flex';
            modelSettings.style.flexDirection = 'column';
        }
        loadModelList();
    }
}

// 加载基础设置
async function loadBasicSettings() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showMessage('您需要登录才能查看设置', 'error');
            return;
        }
        
        const response = await fetch('/api/platform-settings', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        if (!response.ok) {
            throw new Error('获取平台设置失败');
        }
        
        const data = await response.json();
        
        // 填充对话模型选项
        const chatModelSelect = document.getElementById('default-chat-model');
        chatModelSelect.innerHTML = '<option value="">请选择对话模型</option>';
        data.chatModels.forEach(model => {
            const option = document.createElement('option');
            option.value = model.id;
            option.textContent = model.alias;
            if (data.settings.defaultChatModelId === model.id) {
                option.selected = true;
            }
            chatModelSelect.appendChild(option);
        });
        
        // 填充嵌入模型选项
        const embeddingModelSelect = document.getElementById('default-embedding-model');
        embeddingModelSelect.innerHTML = '<option value="">请选择嵌入模型</option>';
        data.embeddingModels.forEach(model => {
            const option = document.createElement('option');
            option.value = model.id;
            option.textContent = model.alias;
            if (data.settings.defaultEmbeddingModelId === model.id) {
                option.selected = true;
            }
            embeddingModelSelect.appendChild(option);
        });
        
    } catch (error) {
        
        showMessage('加载基础设置失败: ' + error.message, 'error');
    }
}

// 保存基础设置
async function saveBasicSettings() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showMessage('您需要登录才能保存设置', 'error');
            return;
        }
        
        const chatModelId = document.getElementById('default-chat-model').value;
        const embeddingModelId = document.getElementById('default-embedding-model').value;
        
        // 获取选中模型的名称用于显示
        const chatModelName = chatModelId ? document.querySelector(`#default-chat-model option[value="${chatModelId}"]`).textContent : '未选择';
        const embeddingModelName = embeddingModelId ? document.querySelector(`#default-embedding-model option[value="${embeddingModelId}"]`).textContent : '未选择';
        
        const settings = {
            defaultChatModelId: chatModelId || null,
            defaultEmbeddingModelId: embeddingModelId || null
        };
        
        const response = await fetch('/api/platform-settings', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(settings)
        });
        
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(errorText);
        }
        
        showMessage(`设置已保存并实时生效！当前对话模型: ${chatModelName}，嵌入模型: ${embeddingModelName}`, 'success');
        
    } catch (error) {
        
        showMessage('保存基础设置失败: ' + error.message, 'error');
    }
}

// 加载模型列表
async function loadModelList() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showMessage('您需要登录才能查看模型列表', 'error');
            return;
        }
        
        const params = new URLSearchParams({
            page: currentPage,
            size: pageSize
        });
        
        if (currentCategory) {
            params.append('category', currentCategory);
        }
        
        if (currentModelType) {
            params.append('modelType', currentModelType);
        }
        
        const response = await fetch(`/api/model-config?${params}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        if (!response.ok) {
            throw new Error('获取模型列表失败');
        }
        
        const data = await response.json();
        renderModelList(data.records);
        renderPagination(data);
        
    } catch (error) {
        
        showMessage('加载模型列表失败: ' + error.message, 'error');
    }
}

// 渲染模型列表
function renderModelList(models) {
    const container = document.getElementById('model-list');
    
    if (models.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-cpu"></i>
                <h4>暂无模型配置</h4>
                <p>点击"添加模型"按钮创建第一个模型配置</p>
            </div>
        `;
        return;
    }
    
    container.innerHTML = models.map(model => `
        <div class="model-item">
            <div class="model-header">
                <div class="model-info">
                    <h4>${model.alias}</h4>
                    <div class="model-meta">
                        <span class="model-tag category">${getCategoryName(model.category)}</span>
                        <span class="model-tag type">${getTypeName(model.modelType)}</span>
                        <span class="model-tag ${model.enabled ? 'enabled' : 'disabled'}">
                            ${model.enabled ? '已启用' : '已禁用'}
                        </span>
                    </div>
                </div>
                <div class="model-actions">
                    <button class="btn btn-sm btn-primary" onclick="editModel(${model.id})">
                        <i class="bi bi-pencil"></i>
                        编辑
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteModel(${model.id})">
                        <i class="bi bi-trash"></i>
                        删除
                    </button>
                </div>
            </div>
            <div class="model-details">
                <p><strong>模型名称:</strong> ${model.modelName}</p>
                ${model.basePath ? `<p><strong>基础路径:</strong> ${model.basePath}</p>` : ''}
                <p><strong>排序号:</strong> ${model.sortOrder || 0}</p>
                <p><strong>创建时间:</strong> ${formatDateTime(model.createTime)}</p>
            </div>
        </div>
    `).join('');
}

// 渲染分页
function renderPagination(data) {
    const container = document.getElementById('model-pagination');
    
    if (data.pages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    let paginationHtml = '<ul class="pagination">';
    
    // 上一页
    if (data.current > 1) {
        paginationHtml += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${data.current - 1})">上一页</a>
            </li>
        `;
    } else {
        paginationHtml += `
            <li class="page-item disabled">
                <span class="page-link">上一页</span>
            </li>
        `;
    }
    
    // 页码
    const startPage = Math.max(1, data.current - 2);
    const endPage = Math.min(data.pages, data.current + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        if (i === data.current) {
            paginationHtml += `
                <li class="page-item active">
                    <span class="page-link">${i}</span>
                </li>
            `;
        } else {
            paginationHtml += `
                <li class="page-item">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        }
    }
    
    // 下一页
    if (data.current < data.pages) {
        paginationHtml += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${data.current + 1})">下一页</a>
            </li>
        `;
    } else {
        paginationHtml += `
            <li class="page-item disabled">
                <span class="page-link">下一页</span>
            </li>
        `;
    }
    
    paginationHtml += '</ul>';
    container.innerHTML = paginationHtml;
}

// 切换页码
function changePage(page) {
    currentPage = page;
    loadModelList();
}

// 过滤模型
function filterModels() {
    currentCategory = document.getElementById('category-filter').value;
    currentModelType = document.getElementById('type-filter').value;
    currentPage = 1;
    loadModelList();
}

// 显示添加模型模态框
function showAddModelModal() {
    document.getElementById('modelModalTitle').textContent = '添加模型';
    document.getElementById('modelForm').reset();
    document.getElementById('model-id').value = '';
    document.getElementById('model-enabled').checked = true;
    
    // 绑定模型分类变化事件
    bindModelCategoryChange();
    
    // 初始设置API秘钥为必填
    updateApiKeyRequirement('');
    
    showModal('modelModal');
}

// 编辑模型
async function editModel(id) {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showMessage('您需要登录才能编辑模型', 'error');
            return;
        }
        
        const response = await fetch(`/api/model-config/${id}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        if (!response.ok) {
            throw new Error('获取模型详情失败');
        }
        
        const model = await response.json();
        
        document.getElementById('modelModalTitle').textContent = '编辑模型';
        document.getElementById('model-id').value = model.id;
        document.getElementById('model-alias').value = model.alias;
        document.getElementById('model-category').value = model.category;
        document.getElementById('model-name').value = model.modelName;
        document.getElementById('model-type').value = model.modelType;
        document.getElementById('model-base-path').value = model.basePath || '';
        document.getElementById('model-api-key').value = model.apiKey || '';
        document.getElementById('model-sort-order').value = model.sortOrder || 0;
        document.getElementById('model-enabled').checked = model.enabled;
        
        // 绑定模型分类变化事件
        bindModelCategoryChange();
        
        // 根据当前分类设置API秘钥必填状态
        updateApiKeyRequirement(model.category);
        
        showModal('modelModal');
        
    } catch (error) {
        
        showMessage('加载模型详情失败: ' + error.message, 'error');
    }
}

// 保存模型
async function saveModel() {
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showMessage('您需要登录才能保存模型', 'error');
            return;
        }
        
        const form = document.getElementById('modelForm');
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }
        
        const id = document.getElementById('model-id').value;
        const modelData = {
            alias: document.getElementById('model-alias').value,
            category: document.getElementById('model-category').value,
            modelName: document.getElementById('model-name').value,
            modelType: document.getElementById('model-type').value,
            basePath: document.getElementById('model-base-path').value || null,
            apiKey: document.getElementById('model-api-key').value || null,
            sortOrder: parseInt(document.getElementById('model-sort-order').value) || 0,
            enabled: document.getElementById('model-enabled').checked
        };
        
        let response;
        if (id) {
            // 更新模型
            response = await fetch(`/api/model-config/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(modelData)
            });
        } else {
            // 创建模型
            response = await fetch('/api/model-config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(modelData)
            });
        }
        
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(errorText);
        }
        
        hideModal('modelModal');
        showMessage(id ? '模型配置已更新并实时生效！如果是当前默认模型，系统已自动重新加载。' : '模型创建成功', 'success');
        loadModelList();
        
        // 如果在基础设置页面，重新加载基础设置
        if (document.getElementById('basic-settings').style.display !== 'none') {
            loadBasicSettings();
        }
        
    } catch (error) {
        
        showMessage('保存模型失败: ' + error.message, 'error');
    }
}

// 删除模型
async function deleteModel(id) {
    if (!confirm('确定要删除这个模型配置吗？')) {
        return;
    }
    
    try {
        const token = localStorage.getItem('token');
        if (!token) {
            showMessage('您需要登录才能删除模型', 'error');
            return;
        }
        
        const response = await fetch(`/api/model-config/${id}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(errorText);
        }
        
        showMessage('模型配置已删除并实时生效！如果删除的是当前默认模型，请重新设置默认模型。', 'success');
        loadModelList();
        
        // 如果在基础设置页面，重新加载基础设置
        if (document.getElementById('basic-settings').style.display !== 'none') {
            loadBasicSettings();
        }
        
    } catch (error) {
        
        showMessage('删除模型失败: ' + error.message, 'error');
    }
}

// 显示模态框
function showModal(modalId) {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    
    modal.classList.add('show');
    modal.style.display = 'flex';
    
    // 阻止页面滚动
    document.body.style.overflow = 'hidden';
    
    // 绑定关闭事件
    const closeBtn = modal.querySelector('.btn-close');
    if (closeBtn) {
        closeBtn.onclick = () => hideModal(modalId);
    }
    
    // 绑定取消按钮事件
    const cancelBtns = modal.querySelectorAll('.btn-secondary');
    cancelBtns.forEach(btn => {
        if (btn.textContent.includes('取消')) {
            btn.onclick = () => hideModal(modalId);
        }
    });
    
    // 点击背景关闭
    modal.onclick = (e) => {
        if (e.target === modal) {
            hideModal(modalId);
        }
    };
    
    // ESC键关闭
    const handleEscKey = (e) => {
        if (e.key === 'Escape') {
            hideModal(modalId);
            document.removeEventListener('keydown', handleEscKey);
        }
    };
    document.addEventListener('keydown', handleEscKey);
}

// 隐藏模态框
function hideModal(modalId) {
    const modal = document.getElementById(modalId);
    modal.classList.remove('show');
    modal.style.display = 'none';
    
    // 恢复页面滚动
    document.body.style.overflow = 'auto';
}

// 获取分类名称
function getCategoryName(category) {
    const names = {
        'openai': 'OpenAI',
        'ollama': 'Ollama',
        'deepseek': 'DeepSeek'
    };
    return names[category] || category;
}

// 获取类型名称
function getTypeName(type) {
    const names = {
        'chat': '对话模型',
        'embedding': '嵌入模型'
    };
    return names[type] || type;
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN');
}

// 显示消息
function showMessage(message, type = 'info') {
    // 创建消息元素
    const messageEl = document.createElement('div');
    messageEl.className = `alert alert-${type === 'error' ? 'danger' : type === 'success' ? 'success' : 'info'}`;
    messageEl.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        padding: 12px 20px;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        max-width: 400px;
    `;
    
    if (type === 'success') {
        messageEl.style.backgroundColor = '#d4edda';
        messageEl.style.color = '#155724';
        messageEl.style.border = '1px solid #c3e6cb';
    } else if (type === 'error') {
        messageEl.style.backgroundColor = '#f8d7da';
        messageEl.style.color = '#721c24';
        messageEl.style.border = '1px solid #f5c6cb';
    } else {
        messageEl.style.backgroundColor = '#d1ecf1';
        messageEl.style.color = '#0c5460';
        messageEl.style.border = '1px solid #bee5eb';
    }
    
    messageEl.textContent = message;
    
    document.body.appendChild(messageEl);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageEl.parentNode) {
            messageEl.parentNode.removeChild(messageEl);
        }
    }, 3000);
}

// 绑定模型分类变化事件
function bindModelCategoryChange() {
    const categorySelect = document.getElementById('model-category');
    categorySelect.addEventListener('change', function() {
        updateApiKeyRequirement(this.value);
    });
}

// 更新API秘钥必填状态
function updateApiKeyRequirement(category) {
    const apiKeyInput = document.getElementById('model-api-key');
    const apiKeyText = apiKeyInput.nextElementSibling;
    
    if (category === 'ollama') {
        // ollama类型API秘钥可选
        apiKeyInput.removeAttribute('required');
        apiKeyText.textContent = '访问模型服务的认证密钥（可选）';
    } else {
        // 其他类型API秘钥必填
        apiKeyInput.setAttribute('required', 'required');
        apiKeyText.textContent = '访问模型服务的认证密钥';
    }
} 